package com.anjie.powerproject.controller;

import com.anjie.powerproject.entity.Device;
import com.anjie.powerproject.entity.GraphDev;
import com.anjie.powerproject.entity.GraphInfo;
import com.anjie.powerproject.entity.StationInfo;
import com.anjie.powerproject.pojo.CustomAtlasDevice;
import com.anjie.powerproject.pojo.CustomAtlasViewDevice;
import com.anjie.powerproject.service.*;
import com.anjie.powerproject.service.impl.GraphDevServiceImpl;
import com.anjie.powerproject.strategy.BaseWorkStrategy;
import com.anjie.powerproject.strategy.pojo.DayWeather;
import com.anjie.powerproject.strategy.pojo.WeatherEachHour;
import com.anjie.powerproject.strategy.service.WeatherForecastService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("strategyJL")
public class StrategyJLController {

    @Autowired
    private PredictDataService predictDataService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private RelationshipService relationshipService;

    @Autowired
    private WeatherForecastService weatherForecastService;

    @Autowired
    private GraphDevServiceImpl graphDevService;

    @Autowired
    private RelationshipController relationshipController;

    @Autowired
    private StationInfoService stationInfoService;
    
    @Autowired
    private BaseWorkStrategy baseWorkStrategy;

    @Autowired
    private PreDataHourService preDataHourService;

    /**
     * 前端需要的绘制电量图、能量图数据
     * @return
     */
    @RequestMapping("/predict_data/{graphId}")
    @ResponseBody
    public Map getPredictData(@PathVariable("graphId")Integer graphId,
                              @RequestParam(defaultValue = "none",value = "date") String dateInfo,
                              @RequestParam(defaultValue = "1001",value = "stgyType") Integer stgyType) throws ParseException {
        Date date = new Date();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        if(!dateInfo.equals("none")){
            date = format1.parse(dateInfo);
        }
        String format = new SimpleDateFormat("yyyy-MM-dd").format(date);
//        format="2022-02-22";
//        graphId=13;
//        System.out.println("format:"+format);

        StationInfo stationInfo=stationInfoService.findStationInfoLimitFirst();
        String batterycode=stationInfo.getBatteryCode();
        String energycode=stationInfo.getEnergyCode();
//      根据graphId去graph info表中获取对应的 strategy_type 值
        GraphInfo graphInfoById = graphInfoService.findGraphInfoById(graphId);

        int[] powerArray = preDataHourService.getPreDataHourValueByCodeAndDateAndGraphIdAndType(format,energycode, graphId,graphInfoById.getStrategyType());
        int[] electricityArray = preDataHourService.getPreDataHourValueByCodeAndDateAndGraphIdAndType(format,batterycode,graphId,graphInfoById.getStrategyType());
        Map map = new HashMap();
        map.put("power",powerArray);
        map.put("electricity",electricityArray);
        map.put("stgyType",stgyType);
        return map;
    }

    /**
     * 根据月份判断显示图谱
     * @return
     * @throws ParseException
     */
    @GetMapping("/getViewAtlas")
    @ResponseBody
    public Map getViewAtlas(@RequestParam(defaultValue = "none",value = "date") String dateInfo) throws ParseException {
        Map map = new HashMap();
        Date date = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        if(!dateInfo.equals("none")){
            date = format1.parse(dateInfo);
        }

//        int graphId = getGraphId(date);
        //Integer graphId = baseWorkStrategy.getGraphId();
        Integer graphId = baseWorkStrategy.getGraphIdByDate(date);
        List<GraphDev> graphDevs = graphDevService.findGraphInfosByGraphId(graphId);
        List res = relationshipController.deviceToCustomAtlasViewDevice(graphDevs);
        if(graphDevs.size() > 0){
            List<Map> edge = relationshipService.getEdgeByGraphId(graphId);
            map.put("edge",edge);
        }else {
            map.put("edge",null);
        }
        GraphInfo graphInfo = graphInfoService.findGraphInfoById(graphId);
        map.put("node",res);
        map.put("graphId",graphId);
        map.put("season",graphInfo.getGraph_type());
        return map;
    }

//    public Integer getGraphId(Date date) throws ParseException {
//        // 目前的图谱不会出现时间重合的现象了，但是可能出现时间空缺的时候，这个时候默认获取上一张图谱
//        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
//        for (GraphInfo graphInfo : graphInfoList) {
//            Date startTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + graphInfo.getGraphStartTime());
//            startTime = DateUtils.plusOrMinusDay(startTime, -1).getTime();
//            Date endTime = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + graphInfo.getGraphEndTime());
//            endTime = DateUtils.plusOrMinusDay(endTime, 1).getTime();
//            // 如果终止时间小于起始时间，说明属于跨年的情况
//            if (endTime.before(startTime)) {
//                Date middleL = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "12-31");
////                Date middleR = DateUtils.ymdFormat.parse(1900 + date.getYear() + "-" + "01-01");
//                Date middleR = DateUtils.ymdFormat.parse(1900 + date.getYear() + 1 + "-" + "01-01");
//					endTime.setYear(endTime.getYear() + 1);
    
////                if (date.after(startTime) && date.before(middleL) || date.before(endTime) && date.after(middleR) || date.equals(middleR) || date.equals(middleL)) {
////                    return graphInfo.getGraphId();
////                }
//                if (date.after(startTime) && date.before(endTime)) {
//                    return graphInfo.getGraphId();
//                }
//            } else {
//                if (date.after(startTime)&&date.before(endTime)){
//                    return graphInfo.getGraphId();
//                }
//            }
//        }
//        // 如果执行到这里，只能说明出现了空缺，找寻前一张图谱
//        GraphInfo beforeGraphInfo = graphInfoService.findBeforeGraphInfo(date);
//        // 原则上这里一定不为空
//        assert beforeGraphInfo != null;
//
//        return beforeGraphInfo.getGraphId();
//    }

    /**
     * 获取设备的高亮图片
     * @param deviceId
     * @return
     */
    @GetMapping("/getHighlightPic/{deviceId}")
    @ResponseBody
    public Map getHighlightPic(@PathVariable("deviceId") Integer deviceId){
        Device device = deviceService.findDeviceById(deviceId);
        Map map = new HashMap();
        if(device == null){
            map.put("msg","fail");
        }else {
            map.put("highlight",device.getHighlightPicPath());
        }
        return map;
    }

    /**
     * 获取每日天气预测
     * @return
     */
    @GetMapping("/getDayWeather")
    @ResponseBody
    public Map getDayWeather(@RequestParam(defaultValue = "none",value = "date") String dateInfo) throws ParseException {
        Map map = new HashMap();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        if(!dateInfo.equals("none")){
            date = format.parse(dateInfo);
        }
        List<StationInfo> infos = stationInfoService.findAllInfo();
        String cityCode = "6587794";//当表中没有数据时，设置默认的
        if(infos != null && infos.size()>0){
            cityCode = infos.get(0).getCityCode();//有多条数据时，默认获取第一条
        }
        DayWeather dayWeather = weatherForecastService.getForecastDayWeatherByDate(date,cityCode);
        List<WeatherEachHour> weatherEachHours = weatherForecastService.getWeatherEachHoursBySdate(date,cityCode);

        if(dayWeather == null || weatherEachHours == null || weatherEachHours.size() == 0){
            map.put("status","0");
            map.put("msg","没有今日天气预测数据");
            return map;
        }
        List<Double> humiditys = new ArrayList<>();
        for(WeatherEachHour w:weatherEachHours){
            humiditys.add(w.getHumidity());
        }

        // 小野修改
        dayWeather.setDes();

        map.put("humidityHigh", Collections.max(humiditys));
        map.put("humidityLow", Collections.min(humiditys));
        map.put("dayWeather",dayWeather);
        map.put("status","1");
        return map;
    }

    /**
     * 吉林页面的多模式保存
     * @param request
     * @return
     */
    @PostMapping("/saveMultiMode")
    @ResponseBody
    public Map saveMultiMode(HttpServletRequest request){
        Map map = new HashMap();
        String graphId = request.getParameter("graphId");
        String strategyType = request.getParameter("strategyType");
        if(graphId != null && strategyType != null && !"".equals(graphId) && !"".equals(strategyType)){
            GraphInfo graphInfo = graphInfoService.findGraphInfoById(Integer.parseInt(graphId));
            if(graphInfo == null){
                map.put("status","图谱不存在"); //图谱不存在
            }else {
                graphInfoService.updateStrategyTypeByGraphId(Integer.parseInt(strategyType),Integer.parseInt(graphId));
                map.put("status","success"); //保存成功
            }
        }else {
            map.put("status","缺少参数"); //缺少参数 graphId 或 strategyType
        }
        return map;
    }

    /**
     * 刚进入页面，将最后一次保存的模式及相关取出并显示
     * @param request
     * @return
     */
    @PostMapping("/viewLastestMultiMode")
    @ResponseBody
    public Map viewLastestMultiMode(HttpServletRequest request){
        Map map = new HashMap();
        String graphId = request.getParameter("graphId");
        if(graphId != null && !"".equals(graphId)){
            GraphInfo graphInfo = graphInfoService.findGraphInfoById(Integer.parseInt(graphId));
            if(graphInfo != null){
                if(graphInfo.getStrategyType() == null){
                    graphInfo.setStrategyType(1001);
                }
                map.put("multimode",graphInfo);
            }else {
                map.put("status", "fail"); //图谱不存在!
            }
        }else {
            map.put("status","fail"); //缺少参数 graphId !
        }
        return map;
    }
}
